package com.example.prjbackend.service;

import java.time.LocalDateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.prjbackend.entity.Department;
import com.example.prjbackend.mapper.DepartmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 新增部门方法
     * @param department 部门对象
     * @return 注册是否成功
     */
    public boolean dept_register(Department department) {
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dept_name", department.getDept_name());
        Long count = departmentMapper.selectCount(queryWrapper);

        if (count > 0) {
            return false; // 部门已存在
        }

        // 插入
        int result = departmentMapper.insert(department);
        return result ==1;
    }

    /***
     * 部门更新方法
     * @param dept_name 需要修改的部门名称
     * @param newDeptDesc 修改的部门内
     * @return 是否成功
     */
    public boolean dept_update(String dept_name,String newDeptDesc) {
        UpdateWrapper<Department> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .eq("dept_name", dept_name)
                .set("dept_desc", newDeptDesc)
                .set("update_time", LocalDateTime.now().toString());

        int updateResult = departmentMapper.update(updateWrapper);
        return updateResult > 0;
    }


    /***
     * 分页查询
     * @param dept_name 待查询部门名
     * @param current 现在的页数
     * @param size 每页的条数
     * @return 分页结果（直接拿总条数、当前页数据）
     */
    public Page<Department> findByDeptname(String dept_name,Long current, Long size) {
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        if (dept_name != null && !dept_name.trim().isEmpty()) {
            queryWrapper.like("dept_name", dept_name); //
        }
        Page<Department> page = new Page<>(current, size);
        return departmentMapper.selectPage(page, queryWrapper);
    }


}
